package com.reactim.message.controller;

import com.reactim.common.response.Result;
import com.reactim.message.connection.CachedConnectionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * 缓存控制器
 * 提供缓存统计和管理API
 */
@RestController
@RequestMapping("/api/cache")
@RequiredArgsConstructor
@Slf4j
@ConditionalOnBean(CachedConnectionManager.class)
public class CacheController {

    private final CachedConnectionManager cachedConnectionManager;

    /**
     * 获取缓存统计信息
     *
     * @return 缓存统计信息
     */
    @GetMapping("/stats")
    public Mono<Result<Map<String, Object>>> getCacheStats() {
        log.debug("获取缓存统计信息");
        return Mono.just(Result.success(cachedConnectionManager.getCacheStats()));
    }

    /**
     * 清除所有缓存
     *
     * @return 操作结果
     */
    @PostMapping("/clear")
    public Mono<Result<Void>> clearAllCaches() {
        log.info("清除所有缓存");
        cachedConnectionManager.clearAllCaches();
        return Mono.just(Result.success());
    }

    /**
     * 刷新缓存（清除并重新加载）
     *
     * @return 操作结果
     */
    @PostMapping("/refresh")
    public Mono<Result<Void>> refreshCache() {
        log.info("刷新缓存");
        cachedConnectionManager.refreshCache();
        return Mono.just(Result.success());
    }

    /**
     * 批量获取用户在线状态
     *
     * @param userIds 用户ID列表
     * @return 用户在线状态映射
     */
    @PostMapping("/online-status/batch")
    public Mono<Result<Map<Long, Boolean>>> batchGetOnlineStatus(@RequestBody List<Long> userIds) {
        log.debug("批量获取用户在线状态: count={}", userIds.size());
        return cachedConnectionManager.batchGetOnlineStatus(userIds)
                .map(Result::success);
    }
}